/**
 * 深度材质分析工具
 * 追踪材质从创建到应用的完整流程
 */

export class DeepMaterialAnalyzer {
    /**
     * 深度分析马路线材质的完整流程
     */
    static analyzeRoadLineMaterial() {
        console.log('\n🔬 深度分析马路线材质流程...\n');
        
        const scene = window.manager?.getCurrentScene()?.scene;
        if (!scene) {
            console.error('❌ 场景未加载');
            return;
        }
        
        // 1. 找到马路线材质
        let roadLineMaterials = [];
        scene.traverse((obj) => {
            if (obj.isMesh && obj.material) {
                const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
                materials.forEach((mat, index) => {
                    const matName = (mat.userData?.materialName || mat.name || '').toLowerCase();
                    const meshName = (obj.name || '').toLowerCase();
                    
                    if (matName.includes('马路') || matName.includes('线') || 
                        meshName.includes('马路') || meshName.includes('线')) {
                        roadLineMaterials.push({
                            mesh: obj,
                            material: mat,
                            materialIndex: index,
                            meshName: obj.name,
                            materialName: mat.userData?.materialName || mat.name
                        });
                    }
                });
            }
        });
        
        if (roadLineMaterials.length === 0) {
            console.log('❌ 未找到马路线材质');
            return;
        }
        
        console.log(`找到 ${roadLineMaterials.length} 个马路线材质:\n`);
        
        roadLineMaterials.forEach((item, index) => {
            const { mesh, material, materialName, meshName } = item;
            
            console.log(`━━━ 马路线材质 ${index + 1}: ${materialName} ━━━`);
            console.log(`Mesh: ${meshName}`);
            
            // 2. 分析材质属性
            console.log(`\n🎨 材质属性分析:`);
            console.log(`   类型: ${material.type}`);
            console.log(`   颜色: RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`);
            console.log(`   颜色十六进制: #${material.color.getHexString()}`);
            console.log(`   透明: transparent=${material.transparent}, alphaTest=${material.alphaTest}, opacity=${material.opacity}`);
            console.log(`   深度: depthWrite=${material.depthWrite}, depthTest=${material.depthTest}`);
            console.log(`   混合: blending=${material.blending}`);
            
            // 3. 分析贴图
            console.log(`\n🖼️ 贴图分析:`);
            if (material.map) {
                console.log(`   主贴图: 存在`);
                console.log(`   贴图URL: ${material.map.image?.src || '未知'}`);
                console.log(`   贴图格式: ${material.map.format}`);
                console.log(`   贴图类型: ${material.map.type}`);
                console.log(`   贴图翻转Y: ${material.map.flipY}`);
                console.log(`   贴图包装: wrapS=${material.map.wrapS}, wrapT=${material.map.wrapT}`);
                
                // 检查贴图是否加载完成
                if (material.map.image) {
                    console.log(`   贴图尺寸: ${material.map.image.width}x${material.map.image.height}`);
                    console.log(`   贴图完成: ${material.map.image.complete}`);
                } else {
                    console.log(`   ⚠️ 贴图图像未加载`);
                }
            } else {
                console.log(`   主贴图: 无`);
            }
            
            if (material.alphaMap) {
                console.log(`   透明贴图: 存在`);
                console.log(`   透明贴图URL: ${material.alphaMap.image?.src || '未知'}`);
            } else {
                console.log(`   透明贴图: 无`);
            }
            
            // 4. 尝试不同的修复方案
            console.log(`\n🔧 尝试修复方案:`);
            
            // 方案1: 纯白色 + alphaTest
            console.log(`方案1: 纯白色 + alphaTest模式`);
            const originalColor = material.color.clone();
            const originalTransparent = material.transparent;
            const originalAlphaTest = material.alphaTest;
            const originalDepthWrite = material.depthWrite;
            
            material.color.setRGB(1, 1, 1);
            material.transparent = false;
            material.alphaTest = 0.5;
            material.depthWrite = true;
            material.needsUpdate = true;
            
            console.log(`   应用: color=白色, transparent=false, alphaTest=0.5, depthWrite=true`);
            
            // 等待一下让用户看效果
            setTimeout(() => {
                console.log(`\n如果方案1无效，尝试方案2...`);
                
                // 方案2: 浅灰色 + transparent
                material.color.setRGB(0.8, 0.8, 0.8);
                material.transparent = true;
                material.alphaTest = 0;
                material.depthWrite = false;
                material.needsUpdate = true;
                
                console.log(`方案2: 浅灰色 + transparent模式`);
                console.log(`   应用: color=浅灰, transparent=true, alphaTest=0, depthWrite=false`);
                
                setTimeout(() => {
                    console.log(`\n如果方案2无效，尝试方案3...`);
                    
                    // 方案3: 检查是否是贴图问题
                    if (material.map) {
                        console.log(`方案3: 检查贴图混合`);
                        material.color.setRGB(1, 1, 1);
                        material.transparent = false;
                        material.alphaTest = 0.1; // 更低的alphaTest
                        material.depthWrite = true;
                        
                        // 尝试不同的贴图设置
                        material.map.premultiplyAlpha = false;
                        material.map.needsUpdate = true;
                        material.needsUpdate = true;
                        
                        console.log(`   应用: 白色 + 低alphaTest(0.1) + 贴图设置调整`);
                    }
                    
                    setTimeout(() => {
                        console.log(`\n🎯 如果所有方案都无效，问题可能在于:`);
                        console.log(`   1. 贴图本身的RGB通道是黑色的`);
                        console.log(`   2. 光照设置问题`);
                        console.log(`   3. 材质混合模式问题`);
                        console.log(`   4. 渲染器设置问题`);
                        
                        // 恢复原始设置用于对比
                        console.log(`\n恢复原始设置用于对比...`);
                        material.color.copy(originalColor);
                        material.transparent = originalTransparent;
                        material.alphaTest = originalAlphaTest;
                        material.depthWrite = originalDepthWrite;
                        material.needsUpdate = true;
                        
                        console.log(`原始设置已恢复`);
                    }, 3000);
                }, 3000);
            }, 3000);
            
            console.log('\n');
        });
        
        return roadLineMaterials;
    }
    
    /**
     * 检查贴图内容
     */
    static analyzeTexture(material) {
        if (!material.map) {
            console.log('❌ 材质没有主贴图');
            return;
        }
        
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = material.map.image;
        
        if (!img || !img.complete) {
            console.log('❌ 贴图未加载完成');
            return;
        }
        
        canvas.width = Math.min(img.width, 100);
        canvas.height = Math.min(img.height, 100);
        
        try {
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
            const data = imageData.data;
            
            let totalR = 0, totalG = 0, totalB = 0, totalA = 0;
            let transparentPixels = 0;
            let blackPixels = 0;
            
            for (let i = 0; i < data.length; i += 4) {
                const r = data[i];
                const g = data[i + 1];
                const b = data[i + 2];
                const a = data[i + 3];
                
                totalR += r;
                totalG += g;
                totalB += b;
                totalA += a;
                
                if (a < 128) transparentPixels++;
                if (r < 50 && g < 50 && b < 50) blackPixels++;
            }
            
            const pixelCount = data.length / 4;
            const avgR = Math.round(totalR / pixelCount);
            const avgG = Math.round(totalG / pixelCount);
            const avgB = Math.round(totalB / pixelCount);
            const avgA = Math.round(totalA / pixelCount);
            
            console.log(`\n🔍 贴图内容分析:`);
            console.log(`   平均颜色: RGB(${avgR}, ${avgG}, ${avgB}), Alpha=${avgA}`);
            console.log(`   透明像素: ${transparentPixels}/${pixelCount} (${(transparentPixels/pixelCount*100).toFixed(1)}%)`);
            console.log(`   黑色像素: ${blackPixels}/${pixelCount} (${(blackPixels/pixelCount*100).toFixed(1)}%)`);
            
            if (avgR < 100 && avgG < 100 && avgB < 100) {
                console.log(`   ⚠️ 贴图整体偏暗，这可能是黑色透明区域的原因！`);
            }
            
        } catch (error) {
            console.log(`❌ 无法分析贴图内容: ${error.message}`);
        }
    }
}

// 暴露到全局
window.deepMaterialAnalyzer = {
    analyze: () => DeepMaterialAnalyzer.analyzeRoadLineMaterial(),
    checkTexture: (materialName) => {
        const scene = window.manager?.getCurrentScene()?.scene;
        if (!scene) return;
        
        scene.traverse((obj) => {
            if (obj.isMesh && obj.material) {
                const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
                materials.forEach((mat) => {
                    const matName = mat.userData?.materialName || mat.name || '';
                    if (matName.includes(materialName)) {
                        DeepMaterialAnalyzer.analyzeTexture(mat);
                    }
                });
            }
        });
    }
};

export default DeepMaterialAnalyzer;
